#
# PHQ9模块
#

import datetime
import time

import pymysql

from DBUtils.PooledDB import PooledDB

from rasa_sdk.executor import CollectingDispatcher

from typing import Text, Dict, Any, List

from rasa_sdk import Action, Tracker
from actions import common


def fix_name(tracker, dispatcher):
    userid = tracker.current_state()['sender_id']
    try:
        x = common.getuserinfo(userid)
        nickname = x[1]
        names = x[2]
        if nickname is None:
            nickname = ''
        if names is None:
            names = ''
        sql = "insert into `user_result`(`id`,`user_info_id`,`topic_type`,`topic_num`,`name`,`nick_name`,`test_batch`) values('" + common.getuid() + "','" + userid + "',1,600,'" + names + "','" + nickname + "'," + str(x[35])+ ");"
        common.connectmysql(sql)
    except:
        dispatcher.utter_message('机器人错误 错误码0x103')


def psq9return(x):
    if 0 <= x <= 4:
        return '没有抑郁症（注意自我保重）'
    elif 5 <= x <= 9:
        return '可能有轻微抑郁症 (建议咨询心理医生或心理医学工作者)'
    elif 10 <= x <= 14:
        return '可能有中度抑郁症, 　(最好咨询心理医生或心理医学工作者)'
    elif 15 <= x <= 19:
        return '可能有中重度抑郁症, (建议咨询心理医生或精神科医生)'
    else:
        return '可能有重度抑郁症 　(一定要看心理医生或精神科医生)'


class ActionPSQ9GreetUser(Action):
    def name(self) -> Text:
        return "action_psq9_question"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        userid = tracker.current_state()['sender_id']
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        try:
            cursor.execute(
                "Select * from `user_result` where `user_info_id` = '" + userid + "' and `topic_type` = 1 and `is_end` = 0 order by create_time desc;")
            old0 = cursor.fetchone()
            if common.rediscommon().get(userid + 'psq9_end'):
                common.rediscommon().delete(userid + 'psq9_end')
                return []
            if old0 in [None, ()]:
                fix_name(tracker, dispatcher)
            cursor.close()
            conn.close()
            conn = common.POOL.connection(shareable=False)
            cursor = conn.cursor()
            cursor.execute(
                "Select * from `user_result` where `user_info_id` = '" + userid + "' and `topic_type` = 1 and `is_end` = 0 order by create_time desc")
            x = cursor.fetchone()
            if x is None:
                cursor.execute(
                    "Select * from `user_result` where `user_info_id` = '" + userid + "' and `topic_type` = 1 and `is_end` = 0 order by create_time desc")
                x = cursor.fetchone()
            if x[5]:
                cursor.execute('Select * from `QA_knowledge_base` where `id`=' + str(
                    x[5]) + ';')
                if str(x[5]) in ['600']:
                    dispatcher.utter_message(text='下面共有9道题目，请仔细阅读每一题，根据您最近一星期的实际情况，做出选择')
                y = cursor.fetchone()
                a = y[8].split(';')
                dispatcher.utter_message(text=y[2], buttons=[
                    {"payload": "/hardly_ever", "title": a[0]},
                    {"payload": "/few_days", "title": a[1]},
                    {"payload": "/more_than_half", "title": a[2]},
                    {"payload": "/every_day", "title": a[3]}
                ], json_message={"module_type": 3})
                return []
        except:
            pass
        finally:
            cursor.close()
            conn.close()


class ActionRestartPsq9Yes(Action):
    def name(self) -> Text:
        return "action_psq9_Restart_yes"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        fix_name(tracker, dispatcher)
        return []


class actionPsq9Save(Action):
    def name(self) -> Text:
        return "action_psq9_save"

    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        userid = tracker.current_state()['sender_id']
        conn = common.POOL.connection(shareable=False)
        cursor = conn.cursor()
        cursor.execute(
            "Select * from `user_result` where `user_info_id` = '" + userid + "' and `topic_type` = 1 and `is_end` = 0 order by create_time desc")
        x = cursor.fetchone()
        name = x[14]
        nickname = x[19]
        test_batch = str(x[20])
        redisc = common.rediscommon()
        if nickname is None:
            nickname = ''
        if name is None:
            name = ''
        try:
            temp = 0
            if 'text' in tracker.current_state()['events'][-2]:
                if tracker.current_state()['events'][-2]['text'] == '/hardly_ever':
                    sql = "update `user_result` set score_psq9=" + str(
                        x[
                            8] + 0) + " where `user_info_id`='" + userid + "' and `topic_type` = 1 and `is_end` = 0 order by create_time desc limit 1;"
                    temp = 0
                    common.connectmysql(sql)
                    if redisc.get(userid + 'rasa_cont'):
                        sqlins = "insert into `user_phq9_question` values('" + common.getuid() + "','" + name + "','" + nickname + "','" + test_batch + "','" + userid + "'," + str(
                            x[5] - 600 + 1) + ",'" + returntitle(x[5] - 600 + 1) + "','几乎不会'," + redisc.get(
                            userid + 'rasa_cont') + ",default,default)"
                    else:
                        sqlins = "insert into `user_phq9_question` values('" + common.getuid() + "','" + name + "','" + nickname + "','" + test_batch + "','" + userid + "'," + str(
                            x[5] - 600 + 1) + ",'" + returntitle(x[5] - 600 + 1) + "','几乎不会',1,default,default)"
                    common.connectmysql(sqlins)
                if tracker.current_state()['events'][-2]['text'] == '/few_days':
                    sql = "update `user_result` set score_psq9=" + str(
                        x[
                            8] + 1) + " where `user_info_id`='" + userid + "' and `topic_type` = 1 and `is_end` = 0 order by create_time desc limit 1;"
                    temp = 1
                    common.connectmysql(sql)
                    if redisc.get(userid + 'rasa_cont'):
                        sqlins = "insert into `user_phq9_question` values('" + common.getuid() + "','" + name + "','" + nickname + "','" + test_batch + "','" + userid + "'," + str(
                            x[5] - 600 + 1) + ",'" + returntitle(x[5] - 600 + 1) + "','有几天'," + redisc.get(
                            userid + 'rasa_cont') + ",default,default)"
                    else:
                        sqlins = "insert into `user_phq9_question` values('" + common.getuid() + "','" + name + "','" + nickname + "','" + test_batch + "','" + userid + "'," + str(
                            x[5] - 600 + 1) + ",'" + returntitle(
                            x[5] - 600 + 1) + "','有几天',1,default,default)"
                    common.connectmysql(sqlins)
                if tracker.current_state()['events'][-2]['text'] == '/more_than_half':
                    sql = "update `user_result` set score_psq9=" + str(
                        x[
                            8] + 2) + " where `user_info_id`='" + userid + "' and `topic_type` = 1 and `is_end` = 0 order by create_time desc limit 1;"
                    temp = 2
                    common.connectmysql(sql)
                    if redisc.get(userid + 'rasa_cont'):
                        sqlins = "insert into `user_phq9_question` values('" + common.getuid() + "','" + name + "','" + nickname + "','" + test_batch + "','" + userid + "'," + str(
                            x[5] - 600 + 1) + ",'" + returntitle(
                            x[5] - 600 + 1) + "','一半以上'," + redisc.get(
                            userid + 'rasa_cont') + ",default,default)"
                    else:
                        sqlins = "insert into `user_phq9_question` values('" + common.getuid() + "','" + name + "','" + nickname + "','" + test_batch + "','" + userid + "'," + str(
                            x[5] - 600 + 1) + ",'" + returntitle(
                            x[5] - 600 + 1) + "','一半以上',1,default,default)"
                    common.connectmysql(sqlins)
                if tracker.current_state()['events'][-2]['text'] == '/every_day':
                    sql = "update `user_result` set score_psq9=" + str(
                        x[
                            8] + 3) + " where `user_info_id`='" + userid + "' and `topic_type` = 1 and `is_end` = 0 order by create_time desc limit 1;"
                    temp = 3
                    common.connectmysql(sql)
                    if redisc.get(userid + 'rasa_cont'):
                        sqlins = "insert into `user_phq9_question` values('" + common.getuid() + "','" + name + "','" + nickname + "','" + test_batch + "','" + userid + "'," + str(
                            x[5] - 600 + 1) + ",'" + returntitle(
                            x[5] - 600 + 1) + "','几乎不会'," + redisc.get(
                            userid + 'rasa_cont') + ",default,default)"
                    else:
                        sqlins = "insert into `user_phq9_question` values('" + common.getuid() + "','" + name + "','" + nickname + "','" + test_batch + "','" + userid + "'," + str(
                            x[5] - 600 + 1) + ",'" + returntitle(
                            x[5] - 600 + 1) + "','几乎不会',1,default,default)"
                    common.connectmysql(sqlins)
            cursor.execute(
                "Select * from `user_result` where `user_info_id` = '" + userid + "' and `topic_type` = 1 and `is_end` = 0 order by create_time desc")
            x = cursor.fetchone()
            sql = "update `user_result` set topic_num=" + str(x[
                                                                  5] + 1) + " where `user_info_id`='" + userid + "' and `topic_type` = 1 and `is_end` = 0 order by create_time desc limit 1;"
            common.connectmysql(sql)
            if x[5] + 1 == 609:
                if redisc.get(userid + 'rasa_cont'):
                    redisc.set(userid + 'rasa_cont',
                               str(int(redisc.get(userid + 'rasa_cont')) + 1))
                else:
                    redisc.set(userid + 'rasa_cont', '2')
                # 记录phq9轮数
                redisc.set(userid + 'psq9_end', '1')
                cursor.execute(
                    "Select * from `user_result` where `user_info_id` = '" + userid + "' and `topic_type` = 1 and `is_end` = 0 order by create_time desc")
                x1 = cursor.fetchone()
                t = common.getuserinfo(userid)
                user_type = t[24]
                user_day7 = t[31]
                user_login = t[30]
                if (user_type == 1) and (user_login == 0):
                    dispatcher.utter_message(text='您已经完成PHQ9的测试啦，让我们继续吧！',
                                             buttons=[{"payload": "/question_chat", "title": "让我们继续吧"}, ],
                                             json_message={"module_type": 1})
                elif (user_type == 2 or user_type == 3) and (user_login == 0):
                    dispatcher.utter_message(text='您已经完成PHQ9的测试啦，让我们继续吧！',
                                             buttons=[{"payload": "/button_first_login_action_5", "title": "让我们继续吧"}, ],
                                             json_message={"module_type": 1})
                elif (user_day7 == 0) and (user_type == 1 or user_type == 2 or user_type == 3):
                    cursor.close()
                    conn.close()
                    conn = common.POOL.connection(shareable=False)
                    cursor = conn.cursor()
                    cursor.execute(
                        "Select * from `user_result` where `user_info_id` = '" + userid + "' and `topic_type` = 1 and `is_end` = 1 order by create_time desc;")
                    old1 = cursor.fetchone()
                    dispatcher.utter_message(
                        text='您上次的分数是' + str(old1[8]) + ',' + psq9return(old1[8]) + '\n您这次的分数是' + str(
                            x1[8] + temp) + ',' + psq9return(x1[8] + temp),
                        buttons=[{"payload": "/button_day_7_after_1", "title": "让我们继续吧"}, ],
                        json_message={"module_type": 1})
                else:
                    dispatcher.utter_message(text='您的分数是' + str(x1[8] + temp) + ',' + psq9return(x1[8] + temp),
                                             buttons=[{"payload": "/greet", "title": "返回首页"}, ])
                sql = "update `user_result` set level_of_depression_psq9='" + psq9return(x[
                                                                                             8]) + "',`is_end` = 1,end_time=now() where `user_info_id` ='" + userid + "' and `topic_type` = 1 order by create_time desc limit 1"
                redisc.close()
                common.connectmysql(sql)
                return []
        except Exception as e:
            dispatcher.utter_message(text='机器人错误 错误码0x007')
        finally:
            cursor.close()
            conn.close()
        return []


def returntitle(num):
    if num == 1:
        return '做事时提不起劲或没有兴趣'
    if num == 2:
        return '感到心情低落、沮丧或绝望'
    if num == 3:
        return '入睡困难、睡不安稳或睡眠过多'
    if num == 4:
        return '感觉疲倦或没有活力'
    if num == 5:
        return '食欲不振或吃太多'
    if num == 6:
        return '觉得自己很糟,或觉得自己很失败,或让自己或家人失望'
    if num == 7:
        return '对事物专注有困难,例如阅读报纸或看电视时不能集中注意力'
    if num == 8:
        return '动作或说话速度缓慢到别人已经觉察?或正好相反,烦躁或坐立不安、动来动去的情况更胜于平常'
    if num == 9:
        return '有不如死掉或用某种方式伤害自己的念头'
